package com.wzz.common.callrecord;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.media.MediaRecorder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class PhoneListener extends PhoneStateListener {
  File audioFile;
  MediaRecorder mediaRecorder;
  Context ctx;
  boolean iscall = false;

  public PhoneListener(Context context) {
    ctx = context;
    iscall = false;
  }

  @Override
  public void onCallStateChanged(int state, String incomingNumber) {
    super.onCallStateChanged(state, incomingNumber);
    mediaRecorder = new MediaRecorder();
    switch (state) {
    case TelephonyManager.CALL_STATE_OFFHOOK:
      iscall = true;
      try {
        recordCallComment();

      } catch (IOException e) {
        e.printStackTrace();
        mediaRecorder.stop();
      }
      Toast.makeText(ctx, "正在录音", Toast.LENGTH_SHORT).show();
      break;
    case TelephonyManager.CALL_STATE_IDLE:
      // if(mediaRecorder!=null){
      // mediaRecorder.stop();
      // mediaRecorder=null;
      // }
      if (iscall) {
        mediaRecorder.stop();
        iscall = false;
      }
      break;
    }
  }

  //
  public void recordCallComment() throws IOException {
    System.out.println(mediaRecorder);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    audioFile = File.createTempFile("record_", ".amr");
    mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
    mediaRecorder.prepare();
    mediaRecorder.start();
  }

}
